﻿using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

namespace OS.Common.Plugs.ConfigPlug
{
    /// <summary>
    /// 读取配置工具
    /// </summary>
    public static class ConfigUtil
    {
        private static readonly DefaultConfigPlug DefaultCache = new DefaultConfigPlug();

        /// <summary>
        /// net core获取全局配置
        /// </summary>
        public static IConfiguration Configuration { get; set; }

        /// <summary>
        /// 通过模块名称获取
        /// </summary>
        /// <param name="configModule">模块名称</param>
        private static IConfigPlug GetConfig(string configModule)
        {
            if (string.IsNullOrEmpty(configModule))
            {
                configModule = "default";
            }

            Func<string, IConfigPlug> configProvider = BaseConfig.ConfigProvider;
            DefaultCache.Configuration = Configuration;
            return configProvider?.Invoke(configModule) ?? DefaultCache;
        }

        /// <summary>
        /// 根据节点名称获取节点
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <param name="moduleName">模块名称</param>
        /// <returns></returns>
        public static IConfigurationSection GetSection(string key, string moduleName = "default")
        {
            return GetConfig(moduleName).GetSection(key);
        }

        /// <summary>
        /// 获取配置文件节连接字符串
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <param name="moduleName">模块名称</param>
        /// <returns></returns>
        public static string GetConnectionString(string name, string moduleName = "default")
        {
            return GetConfig(moduleName).GetConnectionString(name);
        }

        /// <summary>
        /// 获取配置文件子节点
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <returns></returns>
        public static IEnumerable<IConfigurationSection> GetChildren(string moduleName = "default")
        {
            return GetConfig(moduleName).GetChildren();
        }
    }
}